package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.UserMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author by mycp
 * @Classname UserServiceImpl
 * @Description TODO
 * @Date 2018/11/1 12:47
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public void saveOrUpdate(User user) {
        // 判断是更新或者新增
        if (user.getId() == null){
            // 新增
            // 由于注册页面只注册了昵称, 用户名, 密码, 所以用户的其他注册信息需要在后台自动补充设置
            user.setGender(0);
            user.setPlace("中国");
            user.setSign("心有猛虎, 细嗅蔷薇");
            user.setHeadImgUrl("/img/user/head.jpg");
            user.setCoverImgUrl("/img/user/bg.jpeg");
            userMapper.insert(user);
        } else {
            userMapper.updateByPrimaryKey(user);
        }
    }

    @Override
    public void register(User user) {
        // 查询用户名是否已经被注册
        User u = userMapper.checkEmail(user.getEmail());
        if (u != null){
            // 用户名已存在, 抛出异常
            throw  new RuntimeException("注册邮箱已存在, 请重新输入邮箱地址");
        } else {
            // 用户名不存在, 可以注册
            saveOrUpdate(user);
        }
    }

    @Override
    public User login(String password, String email) {
        User user = userMapper.checkUserByEmailAndPassword(password, email);
        if (user == null) {
            // 登录的用户不存在, 抛出异常
            throw new RuntimeException("用户名或密码错误");
        }
        return user;
    }

    @Override
    public PageInfo query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<User> list = userMapper.queryForList(qo);
        return new PageInfo(list);
    }

    @Override
    public User get(Long id) {
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }
}
